package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.entity.BaseBiz;
import com.example.demo.service.BaseBizService;
import com.example.demo.service.DouyinService;
import com.example.demo.util.TokenUtil;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/login")
@AllArgsConstructor
public class LoginController {

    // 假设有一个BaseBizService类来处理业务逻辑
    private final BaseBizService baseBizService;

    private final DouyinService douyinService;


    // 创建BaseBiz实例
    @GetMapping("/getTokenByCode")
    @ResponseBody
    public Result createBaseBiz(HttpServletRequest request) {
        String code = request.getParameter("code");
        Map map = null;
        try {
            map = douyinService.jscode2session(code);
        } catch (Exception e) {
            return Result.fail("登录失败",e.getMessage());
        }
        //根据openid获取用户信息，构建token
        String openid = (String) map.get("openid");
        String sessionkey= (String) map.get("session_key");
        String unionid = (String) map.get("unionid");

        String token = TokenUtil.generatorToken(openid, unionid, sessionkey);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", token);
        resultMap.put("userBiz", map);
        return Result.success(resultMap);
    }

    // 获取BaseBiz实例的详细信息
    @GetMapping("/detail/{id}")
    public BaseBiz getBaseBizDetail(@PathVariable String id) {
        return baseBizService.detail(id);
    }

    // 列出所有BaseBiz实例
    @PostMapping("/list/{page}/{size}")
    public Page<BaseBiz> listBaseBiz(@PathVariable("page") int page,@PathVariable("size") int size,@RequestBody BaseBiz baseBiz) {
        return baseBizService.list(baseBiz,page,size);
    }
}
